<template>
	<view class="page" :style="pageStyle">
		<view style="background-color:#4B4255;height:200px;text-align:center;padding-top:50px;">
			<view style="width:100%;display: block;">
				<text style="color:#FFFFFF;font-size:50rpx;">骑行中</text>
			</view>
			<view style="width:100%;display: block;margin-top:-70upx;">
				<text style="color:#FFFFFF;font-size:160rpx;margin-left:20px;">{{totalDistance}}</text>
				<text style="color:#FFFFFF;">公里</text>
			</view>
			
		</view>
		<map style="width:100%;" :style="mapStyle" :latitude="latitude" :longitude="longitude" :polyline="polyies"></map>
		
		<view style="background-color:#4B4255;height:200px;padding-top:10px;">
			<view style="width:100%;">
				<view style="width:25%;display:inline-block;text-align:center;">
					<text style="color:#FFFFFF;font-size:65rpx;">{{speed}}</text>
				</view>
				<view style="width:50%;display:inline-block;text-align:center;">
					<text style="color:#FFFFFF;font-size:65rpx;">
						{{temp_hour}}:{{temp_minute}}:{{temp_second}}
					</text>
				</view>
				<view style="width:25%;display:inline-block;text-align:center;">
					<text style="color:#FFFFFF;font-size:65rpx;">{{calorie}}</text>
				</view>
			</view>
			
			<view style="width:100%;">
				<view style="width:25%;display:inline-block;text-align:center;">
					<text style="color:#ADACAA;font-size:35rpx;">公里/分钟</text>
				</view>
				<view style="width:50%;display:inline-block;text-align:center;">
					<text style="color:#ADACAA;font-size:35rpx;">用时</text>
				</view>
				<view style="width:25%;display:inline-block;text-align:center;">
					<text style="color:#ADACAA;font-size:35rpx;">千卡</text>
				</view>
			</view>
			
			<view v-if="isRunning" style="text-align:center;width:100%;">
				<cover-image class="img" style="width:80px;height:80px;display:block;margin:0 auto; padding:0;margin-top:10px;" @click="suspend" src="/static/images/suspend.png"></cover-image>
			</view>
			
			<view v-if="!isRunning" style="text-align:center;width:100%;">
				<cover-image class="img" style="width:80px;height:80px;display:inline-block;margin:0 auto; padding:0;margin-top:10px;" @click="goon" src="/static/images/goon.png"></cover-image>
				<cover-image class="img" style="width:80px;height:80px;display:inline-block;margin:0 auto; padding:0;margin-top:10px;" @click="stop" src="/static/images/stop.png"></cover-image>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				latitude: 39.909,
				longitude: 116.39742,
				isRunning: true,
				pageStyle:'',
				mapStyle:'',
				
				temp_totalDistance: 0,
				totalDistance: '0.00',
				isMove: false,
				
				hour: 0, //跑步用时：时
				minute: 0, //跑步用时：分
				second: 0, //跑步用时：秒
				millisecond: 0, //跑步用时：毫秒
				
				temp_hour: '00',
				temp_minute: '00',
				temp_second: '00',
				time_int: '',
				local_int: '',
				
				points: [], //记录跑步过程中定位坐标信息
				
				polyies: [{
					points: [],
					color: "#0000AA",
					width: 5
				}],
				
				calorie:0, //卡路里
				speed:0 //速度
			}
		},
		onShow() {
			this.initView();
		},
		onLoad() {
			this.startTimekeeping();
			this.startGetlocation();
			this.onAccelerometerChange();
			this.getNowLocation();
			// 保持屏幕常亮
			uni.setKeepScreenOn({
				keepScreenOn: true
			});
		},
		onUnload() {
			uni.stopAccelerometer();
		},
		methods: {
			initView:function(){
				var me = this;
				uni.getSystemInfo({
					success: function (res) {
						var screenHeight = res.screenHeight;
						var mapHehight = screenHeight - 400;
						
						me.pageStyle = "height:"+ screenHeight +"px;"; 
						me.mapStyle = "height:"+ mapHehight +"px";
					}
				});
			},
			
			/**
			 * 定位当前位置
			 */
			getMyLocation:function(){
				var me = this;
				if(me.isMove){
					var tem_array = [];
					uni.getLocation({
						type: 'gcj02',
						success: function (res) {
							me.latitude = res.latitude;
							me.longitude = res.longitude;
							if(me.points == null){
								me.points = new Array();
							}else{
								for (var i = 0; i < me.points.length; i++) {
									tem_array.push(me.points[i]);
								}
							}
							var point = {
								latitude: res.latitude,
								longitude: res.longitude
							}
							
							tem_array.push(point);
							me.polyies[0].points = tem_array;
							
							me.points = tem_array;
							me.getDistance();
						}
					});
				}
			},
			
			/**
			 * 定位当前位置
			 */
			getNowLocation:function(){
				var me = this;
				uni.getLocation({
					type: 'gcj02',
					success: function (res) {
						me.latitude = res.latitude;
						me.longitude = res.longitude;
					}
				});
			},
			
			/**
			 * 暂停
			 */
			suspend:function(){
				this.isRunning = false;
				this.stopTimekeeping();
			},
			
			/**
			 * 继续
			 */
			goon:function(){
				this.isRunning = true;
				this.startTimekeeping();
				this.startGetlocation();
			},
			
			/**
			 * 停止
			 */
			stop:function(){
				var me = this;
				if(me.second < 10){
					uni.showModal({
						title: '提示',
						content: '本次运动时间或距离过短，无法保存记录，确定结束吗？',
						confirmColor: '#E0152E',
						cancelColor: "#1AA034",
						cancelText: '继续',
						confirmText: '结束',
						success: function (res) {
							if (res.confirm) {
								me.finish(0);
							} else if (res.cancel) {
								me.goon();
							}
						}
					});
				}else{
					uni.showModal({
						title: '提示',
						content: '确定要结束本次运动吗？',
						confirmColor: '#E0152E',
						cancelColor: "#1AA034",
						cancelText: '继续',
						confirmText: '结束',
						success: function (res) {
							if (res.confirm) {
								me.finish(1);
							} else if (res.cancel) {
								me.goon();
							}
						}
					});
				}
				
			},
			
			/**
			 * 完成
			 */
			finish:function(type){
				var me = this;
				if(type == 0){
					uni.navigateBack({
						delta: 2
					});
				}else{
					var sportHistoryData = uni.getStorageSync('sportHistoryData');
					console.log("从缓存拿出来的" + sportHistoryData.length);
					if(sportHistoryData == null || sportHistoryData == ""){
						sportHistoryData = new Array();
					}
					var time = new Object();
					time.hour = me.hour;
					time.minute = me.minute;
					time.second = me.second;
					
					var sportItem = new Object();
					sportItem.time = time;
					sportItem.totalDistance = me.totalDistance;
					sportItem.speed = me.speed;
					sportItem.calorie = me.calorie;
					sportItem.points = me.points;
					sportItem.type = 0;
					
					var nowDate = new Date();
					//获取当前年
					var year = nowDate.getFullYear();
					
					//获取当前月
					var month = nowDate.getMonth() + 1;
					
					//获取当前日
					var date = nowDate.getDate();
					var h = nowDate.getHours(); //获取当前小时数(0-23)
					var m = nowDate.getMinutes(); //获取当前分钟数(0-59)
					var s = nowDate.getSeconds();
					
					//获取当前时间
					var now = year + '-' + this.conver(month) + "-" + this.conver(date) + " " + this.conver(h) + ':' + this.conver(m) + ":" + this.conver(s);
					
					sportItem.sportTime = now;
					
					sportHistoryData.push(sportItem);
					uni.setStorageSync('sportHistoryData', sportHistoryData);
					uni.redirectTo({
						url: "/pages/sport/finish?detailDate=" + encodeURIComponent(JSON.stringify(sportItem))
					});
				}
			},
			
			/**
			 * 开始计时
			 */
			startTimekeeping:function(){
				var me = this;
				me.time_int = setInterval(me.timekeeping, 50);
			},
			
			/**
			 * 开始定位
			 */
			startGetlocation:function(){
				var me = this;
				me.local_int = setInterval(me.getMyLocation, 3000);
			},
			
			/**
			 * 暂停
			 */
			stopTimekeeping:function(){
				var me = this;
				clearInterval(me.time_int);
				clearInterval(me.local_int);
			},
			
			/**
			 * 计时
			 */
			timekeeping:function(){
				var me = this;
				me.millisecond = me.millisecond + 50;
				if(me.millisecond >= 1000){
					me.millisecond = 0;
					me.second = me.second + 1;
				}
				if(me.second >= 60){
					me.second = 0;
					me.minute = me.minute + 1;
				}
				if(me.minute >= 60){
					me.minute = 0;
					me.hour = me.hour + 1;
				}
				
				if(me.hour < 10){
					me.temp_hour = "0" + me.hour;
				}else{
					me.temp_hour = me.hour;
				}
				
				if(me.minute < 10){
					me.temp_minute = "0" + me.minute;
				}else{
					me.temp_minute = me.minute;
				}
				
				if(me.second < 10){
					me.temp_second = "0" + me.second;
				}else{
					me.temp_second = me.second;
				}
			},
			
			/**
			 * 计算跑步路程
			 */
			getDistance:function(){
				var me = this;
				me.temp_totalDistance = 0;
				//var points = uni.getStorageSync('points');
				if(me.points != null){
					for (var i = 0; i < me.points.length; i++) {
						if(i%2 != 0){
							var latitude1 = me.points[i].latitude;
							var longitude1 = me.points[i].longitude;
							
							var latitude2 = me.points[(i-1)].latitude;
							var longitude2 = me.points[(i-1)].longitude;
							
							var jl = me.calculateDistance(latitude1, longitude1, latitude2, longitude2);
							if(jl != null){
								me.temp_totalDistance = me.temp_totalDistance + jl;
								me.totalDistance = (me.temp_totalDistance*2).toFixed(2);
								me.getcCalorie();
								me.getSpeed();
							}
						}
					}
				}
			},
			
			/**
			 * 经纬度转换成三角函数中度分表形式
			 * @param {Object} d
			 */
			rad:function(d){
				return d * Math.PI / 180.0;
			},
			
			/**
			 * 两个坐标的距离
			 * @param lat1  纬度1
			 * @param lng1  经度1
			 * @param lat2  纬度2
			 * @param lng2  经度2
			 */
			calculateDistance:function(lat1, lng1, lat2, lng2) {
				var me = this;
				let radLat1 = me.rad(lat1);
				let radLat2 = me.rad(lat2);
				let a = radLat1 - radLat2;
				let b = me.rad(lng1) - me.rad(lng2);
				let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
				s = s * 6378.137;// EARTH_RADIUS;
				s = Math.round(s * 10000) / 10000; //输出为公里
				return s;
			},
			
			/**
			 * 监听加速度计数据
			 */
			onAccelerometerChange: function() {
				var me = this;
				uni.onAccelerometerChange(function (res) {
					if(res.x.toFixed(2) > 0.2 || res.y.toFixed(2) > 0.2){
						me.isMove = true;
					}else{
						me.isMove = false;
					}
				});
			},
			
			/**
			 * 计算卡路里
			 */
			getcCalorie: function(){
				var me = this;
				// 消耗热量计算公式：体重（kg）* 距离（km）* 运动系数（k）
				// 运动系数:健走：k=0.8214  跑步：k=1.036  自行车：k=0.6142  轮滑、溜冰：k=0.518  室外滑雪：k=0.888
				var weight = 60;//按照平均体重60KG计算
				var k = 1.036;
				me.calorie = (weight * k * me.totalDistance).toFixed(2);
			},
			
			/**
			 * 计算速度
			 */
			getSpeed: function(){
				var me = this;
				// 跑步总时长，以秒计
				var totalSecond = 0;
				
				//通过跑步的时 分 秒 计算出总时长
				if(me.hour != 0){
					totalSecond = totalSecond + me.hour * 3600;
				}
				if(me.minute != 0){
					totalSecond = totalSecond + me.minute * 60;
				}
				totalSecond = totalSecond + me.second;
				
				//计算速度
				me.speed = (me.totalDistance / totalSecond * 60).toFixed(2);
			},
			
			conver: function(s){
				return s < 10 ? '0' + s : s;
			}
		}
	}
</script>

<style>
</style>
